package com.mall.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mall.constant.MessageConstant;
import com.mall.dto.AfterSalesPageQueryDTO;
import com.mall.exception.BaseException;
import com.mall.po.AfterSales;
import com.mall.mapper.AfterSalesMapper;
import com.mall.po.Orders;
import com.mall.result.PageResult;
import com.mall.service.AfterSalesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.vo.AfterSalesPageQueryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 售后信息 服务实现类
 * </p>
 *
 * @author itlxc
 * @since 2024-04-28
 */
@Service
@RequiredArgsConstructor
public class AfterSalesServiceImpl extends ServiceImpl<AfterSalesMapper, AfterSales> implements AfterSalesService {

    private final AfterSalesMapper afterSalesMapper;

    /**
     * 售后分页查询
     * @param afterSalesPageQueryDTO
     * @return
     */
    @Override
    public PageResult afterSalesPageQuery(AfterSalesPageQueryDTO afterSalesPageQueryDTO) {
        PageHelper.startPage(afterSalesPageQueryDTO.getPage(), afterSalesPageQueryDTO.getPageSize());
        Page<AfterSalesPageQueryVO> page = afterSalesMapper.pageQuery(afterSalesPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 处理售后
     * @param status
     * @param id
     */
    @Override
    @Transactional
    public void handleAfterSales(Integer status, Long id) {
        AfterSales afterSales = getById(id);
        // 判断售后信息是否存在
        if (Objects.isNull(afterSales)) {
            throw new BaseException(MessageConstant.AFTER_SALES_NOT_FOUND);
        }
        Integer type = afterSales.getType();
        // 如果售后类型为仅退款或者退货退款并且为同意状态，需要退款，修改支付状态为退款
        if ((type.equals(AfterSales.REFUND_ONLY) || type.equals(AfterSales.RETURNS_AND_REFUNDS))
                && status.equals(AfterSales.AGREE)) {
            Long orderId = afterSales.getOrderId();
            Orders ordersDB = Db.getById(orderId, Orders.class);
            // 判断订单是否存在
            if (Objects.isNull(ordersDB)) {
                throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
            }
            Orders orders = Orders.builder()
                            .id(ordersDB.getId())
                            .payStatus(Orders.REFUND)
                            .build();
            // 修改订单支付状态
            Db.updateById(orders);
        }
        // 修改售后状态
        AfterSales sales = AfterSales.builder()
                            .id(id)
                            .status(status)
                            .build();
        updateById(sales);

    }
}
